﻿using System.Linq;
using EPiAbstractions.Common.Attributes;
using EPiServer.Common.Attributes;
using EPiServer.Common.Comments;

namespace JoelAbrahamsson.Web.ExtensionMethods
{
    public static class CommentExtensions
    {
        public const string AUTHOR_IP_ATTRIBUTE_NAME = "AuthorIP";

        public static void SetAuthorIP(this Comment comment, string ip)
        {
            EnsureAttributeExists<Comment, string>(AUTHOR_IP_ATTRIBUTE_NAME);

            comment.SetAttributeValue(AUTHOR_IP_ATTRIBUTE_NAME, ip);
        }

        public static string GetAuthorIP(this Comment comment)
        {
            EnsureAttributeExists<Comment, string>(AUTHOR_IP_ATTRIBUTE_NAME);
            
            return comment.GetAttributeValue<string>(AUTHOR_IP_ATTRIBUTE_NAME);
        }

        private static void EnsureAttributeExists<TEntity, TAttribute>(string attributeName)
        {
            if (AttributeHandlerFacade.Instance.GetAttributes(typeof(TEntity)).Count(existingsAttribute => IsMatchingAttribute<TAttribute>(existingsAttribute, attributeName)) > 0)
                return;

            Attribute attribute = new Attribute(attributeName, typeof(TEntity), typeof(TAttribute), false);

            AttributeHandlerFacade.Instance.AddAttribute(attribute);
        }

        private static bool IsMatchingAttribute<TAttribute>(IAttribute existingsAttribute, string attributeName)
        {
            return existingsAttribute.Name == attributeName && existingsAttribute.DataType.Type == typeof(TAttribute);
        }
    }
}
